<template>
  <section v-show="visible" class="field">
    <template v-if="label">
      <div class="field-label">
        <template v-if="required">
          <span class="required">*</span>
        </template>
        {{ label }}
        <span class="result" :class="{'error': error}">
          <icon name="error-icon" />
        </span>
      </div>
    </template>
    <section class="field-body" :class="{'error': error}">
      <component :is="type" ref="field" :option="option" @set-error="fieldCheck" />
      <template v-if="error && error_message">
        <div class="field-error">{{ error_message }}</div>
      </template>
    </section>
    <template v-if="description">
      <div class="field-description">{{ description }}</div>
    </template>
  </section>
</template>
<script>
import mixins from './mixins'
export default {
  name: 'Field',
  componentname: 'Field',
  mixins: [mixins],
  props: {
    type: {
      type: Object,
      default: {}
    },
    option: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      visible: true
    }
  },
  created() {
    this.init()
    this.visible = this.option.visible === undefined ? true : this.option.visible
  },
  methods: {
    init() {
      this.on_event('field-check', (e) => {
        const { data } = e
        this.fieldCheck(data)
        e.stopPropagation()
      })

      this.on_event('filed-value-change', (e) => {
        e.stopPropagation()
        this.dispatch_event('change')
      })
      this.on_event('filed-visible', (e) => {
        e.stopPropagation()
        if (this.option.visible !== undefined) {
          this.visible = this.option.visible
        } else {
          this.visible = e.data
        }
      })
    },

    getValue() {
      const field = this.$refs.field
      if (field && field.getValue) {
        return field.getValue()
      } else {
        return null
      }
    },

    setValue(v) {
      const field = this.$refs.field
      if (field && field.setValue) {
        field.setValue(v)
      }
    },

    fieldCheck({ error, error_message = '必填选项不能为空' }) {
      this.error = error
      this.error_message = error_message
    },

    check() {
      const field = this.$refs.field
      if (field && field.check) {
        return Promise.resolve().then(() => field.check()).then(r => {
          this.fieldCheck({ error: !r })
          return r
        })
      } else {
        return null
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/utility/field.scss';
.field {
  margin-bottom: 15px;
  .field-label {
    @include label();
  }

  .field-body {
    @include body();
  }

  .field-description {
    @include description();
  }
}
</style>
